package com.itboye.ihomebank.activity.key;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.interfaces.IRefreshAfterAlert;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * 发送密码(钥匙)
 */
public class ActivityFaSongPass extends BaseOtherActivity implements Observer {
    View v_statusbar;
    ImageView key_title_finish;
    TextView key_title_title;
    RelativeLayout key_title_xuanze;
    TextView key_title_xuan;
    TextView fasong_time01;
    TextView fasong_time,fasong_shixiao;// 时间
    LinearLayout xuanze_end;//结束生效时间
    TextView fasong_time02,end_time;//结束生效时间
    TextView getPassTv;//发送密码
    EditText passEt;// 密码编辑框

    LinearLayout fasong_duanxin;// 短信发送，微信发送
    private int type = 1;//选择的类型
    KeyPresenter keyPresenter;
    String lockid;
    String lockName;
    String uid;
    long startT, endT;
    long currentTime;
    String password;

    LinearLayout xuanze_shixiao,xuanze_time;
    private TimePickerView pvCustomTime,pvCustomTimeTwo;
    private OptionsPickerView pvOptions;

    private boolean getPass=true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.key_title_finish:
                finish();
                break;
            case R.id.xuanze_shixiao:
            case R.id.fasong_shixiao:// 时效
                pvOptions.show();
                break;
            case R.id.fasong_time01:
            case R.id.fasong_time:
            case R.id.xuanze_time:// 选择开始时间
                pvCustomTime.show(v);//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
                break;
            case R.id.xuanze_end:
            case R.id.fasong_time02:
            case R.id.end_time:// 选择结束时间
                pvCustomTimeTwo.show(v);//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
                break;
            case R.id.fasong_duanxin:// 短信发送，
//                if (fasong_time.getText().toString().equals("")) {
//                    ByAlert.alert("请选择开始日期");
//                    return;
//                }
             String sid=SPUtils.get(this,null,SPContants.LOCK_SESSION,"")+"";
             getPass=false;
            if (password!=null||!password.equals("")){
                String content="您好，您的密码是:"+password+"\n"+"有效期:单次(6小时内使用)"+"\n"+"锁名:"+lockName+"\n\n"+"开锁请按 #密码#（#键也可能是键盘右下角的其它图标键）。";
//                String content="生效时间为:" +getTime(new Date(startT))+ ",有效期为单次(6小时内使用)";

                Uri smsToUri = Uri.parse("smsto:");
                Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
//                intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + password + "," + content);
                intent.putExtra("sms_body", content);
                startActivity(intent);
            }else {
                showProgressDialog("请稍后...", true);
                if ("".equals(sid)){
                    keyPresenter.getKeyboardPwd(uid, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

                }else {
                    keyPresenter.getKeyboardPwd(sid, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

                }
            }

                break;

            case R.id.getPassTv:
                String sid1=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

                getPass=true;
                getPassTv.setEnabled(false);
                if ("".equals(sid1)){
                    keyPresenter.getKeyboardPwd(uid, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

                }else {
                    keyPresenter.getKeyboardPwd(sid1, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

                }
                break;
            case R.id.fasong_weixin:// 微信发送
                ByAlert.alert("开发中，请求期待！");
                break;

            default:
                break;
        }

    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_fasong_pass;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        key_title_title.setText(ActivityGuanLiKey.localKey.getLockAlias());
        key_title_xuan.setText("单次");
        key_title_xuan.setVisibility(View.GONE);
        keyPresenter = new KeyPresenter(this);
        lockid = this.getIntent().getStringExtra("lockid");
        lockName=this.getIntent().getStringExtra("lockName");
//        getOptionData();
        //发送单次密码
        type = 1;
        Date date =new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:00:00 ");
        String time = formatter.format(date);
        try {
            Date parse = formatter.parse(time);
            startT=parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }



//        initOptionPicker();
//        initTimePicker();
//        initTimePickerTwo();
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";

        currentTime = System.currentTimeMillis();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }


    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == KeyPresenter.sendJianPanPass_success) {
                //ByAlert.alert(entity.getData());
//                String type01 = "";
//                if (type == 1) {
//                    type01 = "生效时间为:" + fasong_time.getText().toString() + ",有效期为单次(6小时内使用)";
//                }
//                if (type == 2) {
//                    type01 = "生效时间为:" + fasong_time.getText().toString() + ",有效期为永久";
//                }
//                if (type == 3) {
//                    type01 = "起始日期为:" + fasong_time.getText().toString() + ",结束时间为:"+end_time.getText().toString();
//                }


//                String content = type01;
                password=entity.getData().toString();
                if (getPass){
                    getPassTv.setEnabled(true);
                    passEt.setText(entity.getData().toString());
                    String content1="您好，您的密码是:"+entity.getData().toString()+"\n"+"有效期:单次(6小时内使用)"+"\n"+"锁名:"+lockName+"\n\n"+"开锁请按 #密码#（#键也可能是键盘右下角的其它图标键）。";
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

                    cm.setText(content1);
                    ByAlert.alert("已复制到粘贴板");
                }else {

//                    String content="生效时间为:" +getTime(new Date(startT))+ ",有效期为单次(6小时内使用)";
//
//                    Uri smsToUri = Uri.parse("smsto:");
//                    Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
//                    intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + entity.getData().toString() + "," + content);
//                    startActivity(intent);

                    String content="您好，您的密码是:"+entity.getData().toString()+"\n"+"有效期:单次(6小时内使用)"+"\n"+"锁名:"+lockName+"\n\n"+"开锁请按 #密码#（#键也可能是键盘右下角的其它图标键）。";
//                String content="生效时间为:" +getTime(new Date(startT))+ ",有效期为单次(6小时内使用)";

                    Uri smsToUri = Uri.parse("smsto:");
                    Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
//                intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + password + "," + content);
                    intent.putExtra("sms_body", content);
                    startActivity(intent);
                }

            } else if (entity.getEventType() == KeyPresenter.sendJianPanPass_fail) {
                //获取备用服务器的session
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            } else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData();
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    /**
     * 选择开始时间
     */
    private void initTimePicker() {
        /**
         * @description
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                fasong_time.setText(getTime(date));
                startT = TimesUtils.getStringToDateTwo02(getTime(date));
            }
        })

                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }

    /**
     * 选择结束时间
     */
    private void initTimePickerTwo() {
        /**
         * @description
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTimeTwo = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                end_time.setText(getTime(date));
                endT = TimesUtils.getStringToDateTwo02(getTime(date));
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTimeTwo.returnData();
                                pvCustomTimeTwo.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTimeTwo.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00");
        return format.format(date);
    }
    private ArrayList<String> options1Items = new ArrayList<>();
    /**
     * 选择时效
     */
    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);

                if (options1==0){
                    type = 1;
                    fasong_shixiao.setText("时效："+options1Items.get(options1));
                    xuanze_end.setVisibility(View.GONE);
                }else if (options1==1){
                    type = 2;
                    fasong_shixiao.setText("时效："+options1Items.get(options1));
                    xuanze_end.setVisibility(View.GONE);
                }else{
                    type = 3;
                    fasong_shixiao.setText("时效："+options1Items.get(options1));
                    xuanze_end.setVisibility(View.VISIBLE);
                }
                //   fasong_shixiao.setText(tx+"");
            }
        })
                .setTitleText("请选择密码时效")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptions.setPicker(options1Items);//二级选择器
    }
    private void getOptionData() {
        //选项1
        options1Items.add("单次");
//        options1Items.add("永久");
//        options1Items.add("限时");
    }

    private void toRefreshData() {
        String sid=SPUtils.get(this,null,SPContants.LOCK_SESSION,"")+"";
        if ("".equals(sid)){
            keyPresenter.getKeyboardPwd(uid, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

        }else {
            keyPresenter.getKeyboardPwd(sid, lockid, type + "", "", startT / 1000 + "", type==3?endT / 1000 + "":"",String.valueOf(System.currentTimeMillis()/1000));

        }
    }
}
